package com.example.campuslink.commen.tools

import android.content.Context
import android.content.SharedPreferences
import com.google.gson.Gson

class Sp private constructor() {
    companion object {
        @Volatile
        private var sharedPrefsInstance: SharedPreferences? = null

        @Synchronized
        fun getSharedPrefs(context: Context): SharedPreferences {
            return sharedPrefsInstance ?: synchronized(Sp::class.java) {
                sharedPrefsInstance ?: context.getSharedPreferences(
                    "campus_link",
                    Context.MODE_PRIVATE
                ).also {
                    sharedPrefsInstance = it
                }
            }
        }

        // 存储数组
        fun saveStringArray(context: Context, key: String, array: Array<String>) {

            val gson = Gson()
            val json = gson.toJson(array)
            getSharedPrefs(context).edit().putString(key, json).apply()
        }

        // 读取数组
        fun getStringArray(context: Context, key: String, array: Array<String>): Array<String>? {
            val prefs = getSharedPrefs(context)
            val json = prefs.getString(key, null)
            val gson = Gson()
            return gson.fromJson(json, Array<String>::class.java) // 转回数组
        }

        fun setString(context: Context, key: String, value: String) {
            getSharedPrefs(context).edit().putString(key, value).apply()
        }

        fun setInt(context: Context, key: String, value: Int) {
            getSharedPrefs(context).edit().putInt(key, value).apply()
        }

        fun setBoolean(context: Context, key: String, value: Boolean) {
            getSharedPrefs(context).edit().putBoolean(key, value).apply()
        }


        fun getBoolean(context: Context, key: String, defaultValue: Boolean): Boolean {
            return getSharedPrefs(context).getBoolean(key, defaultValue)
        }

        fun getString(context: Context, key: String, defaultValue: String? = null): String? {
            return getSharedPrefs(context).getString(key, defaultValue)
        }

        fun getInt(context: Context, key: String, defaultValue: Int = 0): Int? {
            return getSharedPrefs(context).getInt(key, defaultValue)
        }

        fun clear(context: Context) {
            getSharedPrefs(context).edit().clear().apply()
        }
    }


}